import Vue from 'vue'
import VueRouter from 'vue-router'
import layout from '@/views/layout'
import login from '@/views/login'
import myorder from '@/views/myorder'
import pay from '@/views/pay'
import prodetail from '@/views/prodetail'
import search from '@/views/search'
import searchList from '@/views/search/list.vue'
import cart from '@/views/layout/cart'
import category from '@/views/layout/category'
import home from '@/views/layout/home'
import user from '@/views/layout/user'
import store from '@/store'
Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    {
      path: '/',
      component: layout,
      redirect: '/home',
      children: [
        { path: 'cart', component: cart },
        { path: 'home', component: home },
        { path: 'user', component: user },
        { path: 'category', component: category }
      ]
    },
    { path: '/login', component: login },
    { path: '/myorder', component: myorder },
    { path: '/pay', component: pay },
    { path: '/prodetail/:id', component: prodetail },
    { path: '/search', component: search },
    { path: '/list', component: searchList }
  ]
})

const authUrl = ['/pay', '/myorder']
router.beforeEach((to, from, next) => {
// ...
// 返回 false 以取消导航
  console.log(to, from)
  if (!authUrl.includes(to.path)) {
    next()
    return
  }
  const token = store.state.user.userInfo.token
  if (token) {
    next()
  } else {
    next('/login')
  }
})

export default router
